package com.example.gobang.api;

import com.example.gobang.model.User;
import com.example.gobang.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * author: hyacinth
 * Date: 2023/5/24
 */
@RestController
public class UserAPI {
    @Autowired
    private UserMapper userMapper;

    /**
     *登录功能
     */
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request){
        User user = userMapper.selectByName(username);
        System.out.println("[login]: username="+username);
        // 用户为空 或 密码不对
        if (user == null || !user.getPassword().equals(password)) {
            System.out.println("登录失败!");
            return new User();
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user);
        return user;
    }

    /**
     * 注册功能
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password){
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);

        } catch (org.springframework.dao.DuplicateKeyException e) {
            user = new User();
        }
        return user;
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request){
        try {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        } catch (NullPointerException e) {
            return new User();
        }
    }
}
